/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Model.DataUltility;

import java.sql.*;

/**
 *
 * @author chickencake1
 */
public class DatabaseConnector {

    public DatabaseConnector() {
    //getConnection();
    }
    
    
    public static Connection getConnection()
    {
        Connection con;
    
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con=DriverManager.getConnection("jdbc:mysql://localhost/greenbookstore?user=root&password=123456&useUnicode=true&characterEncoding=utf8");
            System.out.println("Connect succcess");
             return  con;
        }catch(Exception e){e.printStackTrace();
        System.out.println("Connect fail !!!");
        return null;
        }
       
    }
    
    public static void closeConnection()
    {
        try{
        getConnection().close();
        System.out.println("Closing is successful");
        }catch(Exception e){System.out.println("Closing is fail!!");}
            
    }
    
     public static void executeQueryString(String querystring)
    {
        try
        {
            PreparedStatement st = getConnection().prepareStatement(querystring);
            //Statement st = getConnection().createStatement();
             st.executeUpdate(querystring);
             //System.out.println("Excute success");
            closeConnection(); 
        }catch(Exception e){
            closeConnection();
        e.printStackTrace();}
    }

    
    /**
     * Function : Get result from database-----------------------------------------------------------------------------------
     */
        
    public static ResultSet getResultSet(String querystring){
        try {
            System.out.println(querystring);
            PreparedStatement st = (PreparedStatement) getConnection().prepareStatement(querystring);
            ResultSet rs = st.executeQuery(querystring);         
            System.out.println("selecting success");
            closeConnection();
            return rs;
            
        } catch (Exception e) {
           
           System.out.println("selecting FAIL"); 
           closeConnection();
            return null;
        }
    }
    public static void main(String []argv)
    {
        //DatabaseConnector.getConnection();
        //String query="select * from employee";
        ResultSet re=getResultSet("select * from login_account;");
        String query1="insert into Login_Account(passw) values('vit');";
        executeQueryString(query1);
    }
}
